import logging
from fastapi import APIRouter, status, Depends, BackgroundTasks
from fastapi.security.api_key import APIKey
from sqlalchemy.ext.asyncio import AsyncSession


from . import crud
from . import schemas
from . import dependencies
from price_analysis.auth import auth
from core.models import aux_db_helper
from price_analysis.utils import offer_request as o_r
from price_analysis.utils.mail_sender import send_mail


logger = logging.getLogger("main")

router = APIRouter(tags=["get_offer"])


@router.get("/", status_code=status.HTTP_200_OK)
async def get_data_to_request():
    return await crud.get_items()


@router.post("/", status_code=status.HTTP_200_OK)
async def create_offer(
    api_key: APIKey = Depends(auth.get_api_key),
    session: AsyncSession = Depends(aux_db_helper.get_async_session),
):
    all_items: schemas.ItemList = await crud.get_items()
    sorted_items = await crud.get_sorted_items(session=session, items=all_items)

    offer_request = o_r.OfferRequest(sorted_items)

    return {
        "result": "success",
        "data": offer_request.get_request_templates(),
    }


@router.get("/sent_request/", status_code=status.HTTP_200_OK)
async def send_offer_request(
    tasks: BackgroundTasks,
    dataset: list[dict] = Depends(dependencies.load_dataset),
    api_key: APIKey = Depends(auth.get_api_key),
):
    for partition in dataset:
        message: str = partition["request_templates"]
        providers: list[dict] = partition["providers"]

        for provider in providers:
            tasks.add_task(send_mail, provider["e_mail"], message)

    return {"result": "success"}
